package com.music.glide.manager

import java.util.Collections
import java.util.WeakHashMap


class KActivityFragmentLifecycle : KLifecycle {

    private val lifecycleListeners =
        Collections.newSetFromMap(WeakHashMap<KLifecycleListener, Boolean>())

    private var isStarted = false

    private var isDestroyed = false

    override fun addListener(listener: KLifecycleListener) {
        lifecycleListeners.add(listener)
        if (isDestroyed) {
            listener.onDestroy()
        } else if (isStarted) {
            listener.onStart()
        } else {
            listener.onStop()
        }
    }

    override fun removeListener(listener: KLifecycleListener) {
        lifecycleListeners.remove(listener)
    }

    fun onStart() {
        isStarted = true
        lifecycleListeners.forEach {
            it.onStart()
        }
    }

    fun onStop() {
        isStarted = false
        lifecycleListeners.forEach {
            it.onStop()
        }
    }

    fun onDestroy() {
        isDestroyed = true
        lifecycleListeners.forEach {
            it.onDestroy()
        }
    }
}